package com.h.demo.Service.impl;

import com.h.demo.Service.OrderService;
import com.h.demo.mapper.OrderMapper;
import com.h.demo.modle.OrderInfo;
import com.h.demo.modle.ProductInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;


    @Override
    public OrderInfo getOrderById(Integer orderId) {
        OrderInfo orderInfo =  orderMapper.selectBuId(orderId);

//        String url = "http://127.0.0.1:9090/product/" + orderInfo.getProductId();
        // 从 Eureka 中获取服务列表
        List<ServiceInstance> instances = discoveryClient.getInstances("product-service");
        String uri = instances.get(0).getUri().toString();
        String url = uri + "/product/" + orderInfo.getProductId();
        log.info("url: {}" + url);
        ProductInfo productInfo = restTemplate.getForObject(url, ProductInfo.class);

        orderInfo.setProductInfo(productInfo);

        return orderInfo;
    }
}
